package penguin;

import penguin.masking.Logger;

import java.io.File;
import java.lang.reflect.Method;

/**
 * @author wuxh
 * @version 1.0.0
 */
public class MaskingAttachClient {

    public static void main(String[] args) throws Exception {
        if (args[0] == null) {
            Logger.debug("请输入pid参数");
            return;
        }
        if (args[1] == null) {
            Logger.debug("请输入参数");
            return;
        }
        String pid = args[0];
        String jar = args[1];
        String path = MaskingAttachClient.class.getProtectionDomain().getCodeSource().getLocation().getPath();
        int firstIndex = path.lastIndexOf(System.getProperty("path.separator")) + 1;
        int lastIndex = path.lastIndexOf("/") + 1;
        path = path.substring(firstIndex, lastIndex);
        String jarPath = new File(path, jar).getCanonicalPath();
        Logger.debug(jarPath);
        MaskingAttachClient client = new MaskingAttachClient();
        client.attach(pid, jarPath);
    }

    public boolean attach(String pid, String jar) throws Exception {
        Class<?> vm = Class.forName("com.sun.tools.attach.VirtualMachine");
        Method attach = vm.getMethod("attach", String.class);
        Object o = attach.invoke(vm, pid);
        try {
            Method loadAgent = vm.getMethod("loadAgent", String.class);
            loadAgent.invoke(o, jar);
        } finally {
            Method loadAgent = vm.getMethod("detach");
            loadAgent.invoke(o);
        }
        return true;
    }
}
